package com.hspedu.web.datavalid;

import com.hspedu.web.entity.Car;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Controller;
import org.springframework.validation.BindingResult;
import org.springframework.validation.Errors;
import org.springframework.validation.ObjectError;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.validation.Valid;
import java.util.List;
import java.util.Map;

@Controller
@Scope("prototype")
public class CarHandler {
    @RequestMapping("/addCar")
    public String addCar(Map<String,Object> map){
        map.put("car",new Car());
        for (Map.Entry<String, Object> entry : map.entrySet()) {
            System.out.println("addCar key="+entry.getKey()+"addCar Value="+entry.getValue());
        }
        return "datavalid/car_add";
    }
    @RequestMapping("/saveCar")
    public String saveCar(@Valid Car car, Errors errors, Map<String,Object> map){
        System.out.println("------car------"+car);
        for (Map.Entry<String, Object> entry : map.entrySet()) {
            System.out.println("key="+entry.getKey()+"  value="+entry.getValue());
        }
        System.out.println("==========error==========");
        if (errors.hasErrors()){
            List<ObjectError> allErrors = errors.getAllErrors();
            for (ObjectError allError : allErrors) {
                System.out.println("error="+allError);
            }
            return "datavalid/car_add";
        }
        return "datavalid/success";
    }

}
